package com.xht.authorization.server.endpoint;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;
import java.util.Set;

/**
 * <h1>描述 ：端点</h1>
 *
 * @author : 小糊涂
 * @version : 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthorizationServerEndpoint {


    /**
     * 登录认证页面
     */
    @GetMapping("/login.html")
    public ModelAndView require(ModelAndView modelAndView,
                                @RequestParam(required = false) String error) {
        modelAndView.setViewName("ftl/login");
        modelAndView.addObject("error", error);
        return modelAndView;
    }

    /**
     * 授权页面
     */
    @GetMapping("/confirm_access.html")
    public ModelAndView confirm(Principal principal,
                                ModelAndView modelAndView,
                                @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId,
                                @RequestParam(OAuth2ParameterNames.SCOPE) String scope,
                                @RequestParam(OAuth2ParameterNames.STATE) String state) {
        log.info("授权页面跳转 principal={},clientId={},scope={},state={}", principal, clientId, scope, state);
        Set<String> authorizedScopes = StringUtils.commaDelimitedListToSet(scope);
        modelAndView.addObject("clientId", clientId);
        modelAndView.addObject("state", state);
        modelAndView.addObject("scopeList", authorizedScopes);
        modelAndView.addObject("principalName", principal.getName());
        modelAndView.setViewName("ftl/confirm");
        return modelAndView;
    }

}
